﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TByte.XnaHelper.GameObjects;

namespace TByte.XnaHelper.GameObjects
{
    public class AnimationManager : GameObject
    {
        #region Fields
        string currentAnimation;
        string defaultAnimation;
        #endregion

        #region Methods
        public void Play(string name, bool loop = false, bool reset = false)
        {
            currentAnimation = name;
            foreach (GameObject go in children)
            {
                AnimationGameObject animation = go as AnimationGameObject;
                if (animation != null)
                {
                    animation.Looping = loop;
                    animation.Visible = animation.Playing = animation.Name == name;
                    if (reset)
                        animation.Reset();
                }
            }
        }
        public override void AddChild(GameObject gameObject)
        {
            //Subscribe to stop event
            AnimationGameObject animation = gameObject as AnimationGameObject;
            if(animation != null)
                animation.AnimationFinished += new AnimationGameObject.AnimationFinishedEventHandler(AnimationFinished);

            base.AddChild(gameObject);
        }
        void AnimationFinished(AnimationGameObject animation)
        {
            //Stop and hide the animation
            animation.Playing = false;
            animation.Visible = false;

            //resume default
            if (defaultAnimation != string.Empty)
                Play(defaultAnimation, true);
        }
        public void SetDefaultAnimation(string defaultAnimation)
        {
            GameObject test = FindObject(defaultAnimation);
            if (FindObject(defaultAnimation) as AnimationGameObject != null)
            {
                this.defaultAnimation = defaultAnimation;
            }
        }
        #endregion

        #region Constructors
        public AnimationManager(string name)
            : base(name)
        {

        }
        #endregion

        #region Properties
        public AnimationGameObject CurrentAnimation { get { return FindObject(currentAnimation) as AnimationGameObject; } }
        public bool Mirror { get { return CurrentAnimation.Mirror; } set { CurrentAnimation.Mirror = value; } }
        #endregion
    }
}
